/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.controller;

import com.vng.zing.survey.memcached.SurveyCache;
import com.vng.zing.survey.thrift.client.SurveyClient;
import com.vng.zing.survey.thrift.model.AnswerItem;
import com.vng.zing.survey.thrift.model.QuesType;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.vng.zing.survey.model.CommonModel.OFFSET;
import com.vng.zing.survey.model.CommonModel;
import com.vng.zing.survey.thrift.model.UserType;
import java.util.Map;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class AjaxStatisticController extends BaseController {

    private static UserType userType = UserType.USER;

    @Override
    public String render(HttpServletRequest request, HttpServletResponse resp) throws IOException, Exception {
      
        if (request.getParameter("page") == null || request.getParameter("idSurvey") == null || request.getParameter("idQuestion") == null) {
            return CommonModel.toJSON("ERROR", "Tham số không hợp lệ!");
        }
        try {
            Integer page = Integer.parseInt(request.getParameter("page"));
            page--;
            String type = request.getParameter("type");
            Short idQuestion = Short.parseShort(request.getParameter("idQuestion"));
            Integer idSurvey = Integer.parseInt(request.getParameter("idSurvey"));

            Map map = checkMember(request, userType);
            if (map.containsValue(ErrorType.FAIL) || map.containsValue(ErrorType.ERROR_SYSTEM)) {
                return CommonModel.toJSON("ERROR", (String) map.get("msg"));
            }
            int idUser = (int) map.get("msg");
            boolean isAdmin = (boolean) map.get("admin");

            SurveyClient surveyClient = SurveyClient.getInstance();
            SurveyItemResult itemResult = SurveyCache.getSurveyWithCache(idSurvey);
            if (itemResult.getErro() != com.vng.zing.survey.thrift.model.Error.SUCCESS || itemResult.getSurveyItem().getIDUser() != idUser) {
                return CommonModel.toJSON("ERROR", "Đã có lỗi xảy ra!");
            }
            if (itemResult.getSurveyItem().isOption() == false && !isAdmin) {
                return CommonModel.toJSON("ERROR", "Đã có lỗi xảy ra!");
            }
            TemplateDataDictionary dicAnswers = TemplateDictionary.create();
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
            Date date;
            List<AnswerItem> answerItems = surveyClient.getResByQues(idSurvey, idQuestion, page, OFFSET);
            if (type != null && type.equals(QuesType.MULTI_LINE.name())) {

                for (int i = 0; i < answerItems.size(); i++) {
                    TemplateDataDictionary sliceAnswer = dicAnswers.addSection("SLICE_ANSWER");
                    sliceAnswer.setVariable("NUMBER", String.format("%s", page * OFFSET + i + 1));
                    sliceAnswer.setVariable("USERNAME",  answerItems.get(i).getDisplayName());
                    sliceAnswer.setVariable("CONTENT", answerItems.get(i).getAnswer());
                    date = new Date(((long) answerItems.get(i).getTimeResponse()) * 1000L);
                    sliceAnswer.setVariable("TIMERESPONSE", df.format(date));
                }

//           
                return CommonModel.getStatMutilLine(dicAnswers);

            } else {

                for (int i = 0; i < answerItems.size(); i++) {
                    TemplateDataDictionary sliceAnswer = dicAnswers.addSection("SLICE_ANSWER");
                    sliceAnswer.setVariable("NUMBER", String.format("%s", page * OFFSET + i + 1));
                    sliceAnswer.setVariable("USERNAME", String.format("%s", answerItems.get(i).getDisplayName()));
                    sliceAnswer.setVariable("CONTENT", answerItems.get(i).getAnswer());
                    date = new Date(((long) answerItems.get(i).getTimeResponse()) * 1000L);
                    sliceAnswer.setVariable("TIMERESPONSE", df.format(date));
                }
                return CommonModel.getStatTable(dicAnswers);
            }
           
           
        } catch (Exception ex) {
             Logger.getLogger(this.getName()).error(ex.toString());
            CommonModel.toJSON("ERROR", "");
        }
         return CommonModel.toJSON("ERROR", "");
    }
}
